//
//  StudyController.m
//  TrainTree
//
//  Created by wanghui on 2017/8/24.
//  Copyright © 2017年 YouYeShu. All rights reserved.
//

#import "StudyController.h"

#import "StudyRequestManager.h"
#import "TopCell.h"
#import "CourseCell.h"
#import <QuickLook/QuickLook.h>
#import "QuickLookFileController.h"
#import "StudySectionHeader.h"
#import "SearchController.h"
#import "CourseDetailController.h"
#import "CourseAudioVideoController.h"

@interface StudyController ()<UITableViewDelegate,UITableViewDataSource,StudyBannerToNextPageDelegate>
{
    StudySectionHeader *_header;
}
/**文件地址*/
@property(nonatomic,copy) NSString *filePath;
@property (strong, nonatomic) UITableView *mainTableView;
/**轮播图数组*/
@property (nonatomic, strong) NSArray *picArrs;
/**必修选修*/
@property (nonatomic, assign) StudyType studyType;
/**必修选修数组*/
@property (nonatomic, strong) NSMutableArray *courseArray;
@end

@implementation StudyController
- (void)viewWillAppear:(BOOL)animated
{
    if (![Session isLogin]) {
        [Login presentLoginPage];
    }

    [self requestLessonData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationView.title = @"学习";
    self.studyType = StudyTypeRequired;

    [self.navigationView.leftBtn addTarget:self action:@selector(searchBtnClick ) forControlEvents:UIControlEventTouchUpInside];
    [self setTableView];

    [self loadCarouselData];
    [self requestLessonData];

}
#pragma  mark - 轮播图
- (void)loadCarouselData
{
//    [CommonRequestManager getBannerListResponse:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {
//
//    }];

    self.picArrs = [BannerData shareBannerData].bannerArray;
    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:0];
    [self.mainTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];

}
- (void)setTableView
{
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, ScreenWidth, ScreenHeight - 60 - 49) style:UITableViewStylePlain];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.view addSubview:self.mainTableView];
}

- (void)searchBtnClick
{
    self.hidesBottomBarWhenPushed = YES;
    SearchController *searchVc = [[SearchController alloc]init];
    [self.navigationController pushViewController:searchVc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

#pragma  mark - 请求列表数据
- (void)requestLessonData
{
//    UIActivityIndicatorView *load = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(ScreenWidth / 2 - 25, ScreenHeight / 2 - 25, 50, 50)];
//
//    load.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
//    load.alpha = 0.5;
//    [self.view addSubview:load];
//    [load startAnimating];
//
//    [load stopAnimating];
//    [load removeFromSuperview];

    WeakSelf(ws);
    [StudyRequestManager getStudyType:self.studyType Response:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {
        if (JSONData) {
                // 在赋值前先清空数组
            [ws.courseArray removeAllObjects];
            if ([JSONData[@"c"] intValue] == 0) {
                NSArray *dataArray = [NSArray arrayWithArray:JSONData[@"d"]];

                for (NSDictionary *dic in dataArray) {
                    StudyCourseModel *model = [StudyCourseModel mj_objectWithKeyValues:dic];
                    [ws.courseArray addObject:model];
                }
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
                [ws.mainTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
            }else{

                [SVProgressHUD showErrorWithStatus:JSONData[@"m"]];
            }
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
            [ws.mainTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
        }
    }];

}
#pragma mark - tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else {
        return self.courseArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return ScreenWidth * 160 / 375;
    }else{
        return  60;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        _header = [LoadXibTool loadViewFromXibName:@"StudySectionHeader"];
        [_header.myRequiredCourse addTarget:self action:@selector(myRequiredClick) forControlEvents:UIControlEventTouchUpInside];

        [_header.myOptionalCourse addTarget:self action:@selector(myOptionalClick) forControlEvents:UIControlEventTouchUpInside];

        // 刷新后会重新加载sectionHeader。判断UI
        if (self.studyType == StudyTypeRequired){
            _header.showRequiredLine = YES;
        }else{
            _header.showRequiredLine = NO;
        }
        return _header;
    }else{
        return nil;
    }
}
#pragma  mark - 点击必修课
- (void)myRequiredClick
{
    _header.showRequiredLine = YES;
    self.studyType = StudyTypeRequired;
    [self  requestLessonData];
}

#pragma  mark - 点击选修课
- (void)myOptionalClick
{
    _header.showRequiredLine = NO;
    self.studyType = StudyTypeOptional;
    [self  requestLessonData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 42;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        TopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopCell"];
        if (!cell) {
            cell = [LoadXibTool loadViewFromXibName:@"TopCell"];
        }
        [cell configWithArray:self.picArrs];
        cell.delegate = self;
        return cell;
        

    }else {
        CourseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CourseCell"];
        if (!cell) {
            cell = [LoadXibTool loadViewFromXibName:@"CourseCell"];
        }

        [cell adjustProgressWithData:self.courseArray[indexPath.row] withType:self.studyType];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section > 0) {
        CourseDetailController *courseVc = [[CourseDetailController alloc]init];
        if (self.courseArray.count > 0) {
            StudyCourseModel *model = self.courseArray[indexPath.row];
            courseVc.lessonId = model.lessonId ;
        }
        [self.navigationController pushViewController:courseVc animated:YES];
    }

}
#pragma mark - 根据轮播图传递ID和type跳往知识点或者课程详情页
- (void)studyBannerToNextPageWithType:(NSString *)type lessonId:(NSString *)lessonId
{
    if ([type intValue] == 0) {// 跳往课程
        self.hidesBottomBarWhenPushed = YES;
        CourseDetailController *vc = [[CourseDetailController alloc]init];
        vc.lessonId = lessonId;
        [self.navigationController pushViewController:vc animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    } else if ([type intValue] == 1) {// 跳往知识点
        self.hidesBottomBarWhenPushed = YES;
        CourseAudioVideoController *vc = [[CourseAudioVideoController alloc]init];
        vc.pointId = lessonId;
        [self.navigationController pushViewController:vc animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    } else{

    }
}

#pragma mark - 预览文件 
- (void)presentToQuickLook:(NSString *)path
{
    QuickLookFileController *quickVc = [[QuickLookFileController alloc]init];
    quickVc.filePath = path;
    [self.navigationController pushViewController:quickVc animated:YES];
}

#pragma  mark - 懒加载
- (NSMutableArray *)courseArray
{
    return _courseArray ?: (_courseArray = [[NSMutableArray alloc]init]);
}
- (NSArray *)picArrs
{
    return _picArrs ?: (_picArrs = [[NSArray alloc] init]);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
